<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use App\Models\User;
use App\Models\PostView;
use Illuminate\Http\Request;
use Inertia\Inertia;

class BlogController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();

        $posts = Post::with(['user', 'category', 'tags'])
            ->published()
            ->approved()
            ->accessibleBy($user)
            ->when($request->search, function ($query, $search) {
                return $query->where(function ($q) use ($search) {
                    $q->where('title', 'like', "%{$search}%")
                        ->orWhere('content', 'like', "%{$search}%");
                });
            })
            ->when($request->category, function ($query, $category) {
                return $query->whereHas('category', function ($q) use ($category) {
                    $q->where('slug', $category);
                });
            })
            ->when($request->tag, function ($query, $tag) {
                return $query->whereHas('tags', function ($q) use ($tag) {
                    $q->where('slug', $tag);
                });
            })
            ->orderBy('is_sticky', 'desc')
            ->orderBy('published_at', 'desc')
            ->paginate(10);

        $featuredPosts = Post::with(['user', 'category', 'tags'])
            ->published()
            ->featured()
            ->take(3)
            ->get();

        $categories = Category::withCount('posts')
            ->where('is_active', true)
            ->get();

        $popularTags = Tag::withCount('posts')
            ->orderBy('posts_count', 'desc')
            ->take(20)
            ->get();

        return Inertia::render('Blog/Index', [
            'posts' => $posts,
            'featuredPosts' => $featuredPosts,
            'categories' => $categories,
            'popularTags' => $popularTags,
            'filters' => $request->only(['search', 'category', 'tag'])
        ]);
    }

    public function show(string $slug)
    {
        $user = auth()->user();

        $post = Post::with(['user', 'category', 'tags', 'comments' => function ($query) {
            $query->approved()->with('user')->parent();
        }])
            ->where('slug', $slug)
            ->published()
            ->approved()
            ->firstOrFail();

        // 检查用户是否有权限查看
        if (!$user && $post->access_level !== 'public') {
            // 未登录用户只能查看公开文章
            if ($post->access_level === 'login_required') {
                // 可以查看部分内容，但需要在前端处理
                // 传递一个标志表示需要登录查看完整内容
                $post->needs_login = true;
            } else {
                abort(403, '您没有权限查看此文章');
            }
        } elseif ($user && !$user->canViewPost($post)) {
            abort(403, '您没有权限查看此文章');
        }

        // 记录浏览历史
        PostView::recordView($post, $user);

        // 判断用户是否关注了作者
        $isFollowing = $user ? $user->isFollowing($post->user) : false;

        // 相关文章（只显示用户有权限查看的）
        $relatedPostsQuery = Post::published()
            ->approved()
            ->accessibleBy($user)
            ->where('id', '!=', $post->id)
            ->where(function ($query) use ($post) {
                $query->where('category_id', $post->category_id)
                    ->orWhereHas('tags', function ($q) use ($post) {
                        $q->whereIn('tags.id', $post->tags->pluck('id'));
                    });
            });

        $relatedPosts = $relatedPostsQuery->take(4)->get();

        // 为文章添加权限相关信息
        $post->can_view_full = !isset($post->needs_login) || $user;
        $post->is_following_author = $isFollowing;

        return Inertia::render('Blog/Show', [
            'post' => $post,
            'relatedPosts' => $relatedPosts,
            'isAuthenticated' => (bool) $user,
            'canComment' => $user && $post->allow_comments,
        ]);
    }

    public function category(string $slug)
    {
        $category = Category::where('slug', $slug)
            ->where('is_active', true)
            ->firstOrFail();

        $posts = Post::with(['user', 'tags'])
            ->published()
            ->where('category_id', $category->id)
            ->orderBy('published_at', 'desc')
            ->paginate(10);

        return Inertia::render('Blog/Category', [
            'category' => $category,
            'posts' => $posts
        ]);
    }

    public function tag(string $slug)
    {
        $tag = Tag::where('slug', $slug)->firstOrFail();

        $posts = Post::with(['user', 'category'])
            ->published()
            ->whereHas('tags', function ($query) use ($tag) {
                $query->where('tags.id', $tag->id);
            })
            ->orderBy('published_at', 'desc')
            ->paginate(10);

        return Inertia::render('Blog/Tag', [
            'tag' => $tag,
            'posts' => $posts
        ]);
    }

    public function author(string $username)
    {
        $author = User::where('username', $username)
            ->where('status', 'active')
            ->firstOrFail();

        $posts = Post::with(['category', 'tags'])
            ->published()
            ->where('user_id', $author->id)
            ->orderBy('published_at', 'desc')
            ->paginate(10);

        return Inertia::render('Blog/Author', [
            'author' => $author,
            'posts' => $posts
        ]);
    }
}